using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace Starznet.SharePoint.SPDAT.ApplicationPages.Settings
{
    public class MembershipEditUserPage : LayoutsPageBase
    {
        protected InputFormTextBox TxtUsername;
        protected InputFormTextBox TxtQuestion;
        protected InputFormTextBox TxtAnswer;
        protected InputFormTextBox TxtEmail;
        protected InputFormCheckBox ChkLockedOut;
        protected Label LblUserName;
        protected PeopleEditor PeopleEditorRoles;
        protected PeopleEditor PeopleEditorSPGroups;
        protected Label AddUserError;
        protected InputFormSection IFSQandA;

        private MembershipUser _oUsr;

        protected override void  OnLoad(EventArgs e)
        {
 	        base.OnLoad(e);

            string sUserName = Request.QueryString.Get("UserName");
            if (string.IsNullOrEmpty(sUserName))
                throw new ArgumentException("A UserName must be supplied");

            IFSQandA.Visible = Membership.RequiresQuestionAndAnswer;

            _oUsr = Membership.GetUser(sUserName);

            if (!IsPostBack)
            {
                LblUserName.Text = _oUsr.UserName;
                TxtEmail.Text = _oUsr.Email;
                ChkLockedOut.Checked = _oUsr.IsLockedOut;
                if (Roles.Enabled)
                {
                    foreach (string sRole in Roles.GetRolesForUser(_oUsr.UserName))
                        PeopleEditorRoles.Entities.Add(sRole);
                }
            }

            PeopleEditorRoles.Enabled = Roles.Enabled;
        }

        protected void BtnUpdateUser_Click(object sender, EventArgs e)
        {
            _oUsr.Email = this.TxtEmail.Text;

            if (!ChkLockedOut.Checked && _oUsr.IsLockedOut)
                _oUsr.UnlockUser();

            if (Roles.Enabled)
            {
                Roles.RemoveUserFromRoles(_oUsr.UserName, Roles.GetRolesForUser(_oUsr.UserName));
                foreach (PickerEntity oEntity in PeopleEditorRoles.Entities)
                    Roles.AddUserToRole(_oUsr.UserName, oEntity.Key);
            }
        }

        protected void ValidateEmail(object sender, ServerValidateEventArgs args)
        {
            if (_oUsr.Email != this.TxtEmail.Text)
            {
                if (Membership.FindUsersByEmail(this.TxtEmail.Text).Count > 0)
                    args.IsValid = false;
            }
        }

    }
}
